import java.util.*;

/**
 * 剑指 Offer 32 - I. 从上到下打印二叉树
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
 */
public class Solutions_Offer_32_I {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        int[] result = levelOrder(root);
        System.out.println(Arrays.toString(result));
    }

    // 使用广度优先搜索并借助 Queue 实现
    public static int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        List<Integer> resList = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);
        while (!queue.isEmpty()) {
            // 二叉树第 n 层上，结点的个数为 size 个
            int size = queue.size();
            // 循环将该层上的节点对象，弹出队列并进行结果集记录与不为 null 的左右子节点入队的操作
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                // 记录节点值
                resList.add(node.val);
                // 左右子节点对象不为 null 时，加入到队列中
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        return res;
    }
}
